package com.laojiang.imagepickers.ui.camera;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;


import com.cjt2325.cameralibrary.JCameraView;
import com.cjt2325.cameralibrary.listener.ClickListener;
import com.cjt2325.cameralibrary.listener.ErrorListener;
import com.cjt2325.cameralibrary.listener.JCameraListener;
import com.cjt2325.cameralibrary.util.FileUtil;
import com.laojiang.imagepickers.R;
import com.laojiang.imagepickers.base.activity.ImagePickerBaseActivity;
import com.laojiang.imagepickers.data.ImageContants;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static com.cjt2325.cameralibrary.JCameraView.BUTTON_STATE_ONLY_CAPTURE;

/**
 * 类介绍（必填）：
 * Created by Jiang on 2017/7/31 14:46.
 */

public class DiyCameraActivity extends ImagePickerBaseActivity {

    private final int GET_PERMISSION_REQUEST = 100; //权限申请自定义码
    private JCameraView jCameraView;
    private boolean granted = false;
    private View decorView;
    private String cachePath;
    private boolean isNeedVideo;

   /* public static void start(Activity context, String path) {
        Intent starter = new Intent(context, DiyCameraActivity.class);
        starter.putExtra("cachePath", path);
        context.startActivityForResult(starter, ImageContants.CAMERA_REQUEST);
    }*/

    public static void start(Activity context, String path, boolean isNeedVideo) {
        Intent starter = new Intent(context, DiyCameraActivity.class);
        starter.putExtra("cachePath", path);
        starter.putExtra("isNeedVideo", isNeedVideo);
        context.startActivityForResult(starter, ImageContants.CAMERA_REQUEST);
    }

    /**
     * Fragment中直接启动拍照
     * @param context 上下文
     * @param path 路径
     * @param isNeedVideo 是否需要视频
     */
    public static void start(Fragment context, String path, boolean isNeedVideo) {
        Intent starter = new Intent(context.getActivity(), DiyCameraActivity.class);
        starter.putExtra("cachePath", path);
        starter.putExtra("isNeedVideo", isNeedVideo);
        context.startActivityForResult(starter, ImageContants.CAMERA_REQUEST);
    }


    @Override
    protected int getContentViewResId() {
        return R.layout.camera_intent;
    }

    @Override
    protected void initUI(View contentView) {
        getPermissions();
        hindSystemUI();
        //认为他要拍照
        SharedPreferences sp = getSharedPreferences("issafe", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("safe", true);
        editor.apply();
        jCameraView = (JCameraView) findViewById(R.id.jcameraview);
        if (!isNeedVideo) {
            //不需要录制视频
            jCameraView.setFeatures(BUTTON_STATE_ONLY_CAPTURE);
            jCameraView.setTip("轻触拍照");

        }
        //设置视频保存路径
        jCameraView.setSaveVideoPath(Environment.getExternalStorageDirectory().getPath() + File
                .separator + "MyAppPic");

        //JCameraView 监听
        jCameraView.setErrorLisenter(new ErrorListener() {
            @Override
            public void onError() {
                //打开 Camera 失败回调
                Log.i("CJT", "open camera error");
            }

            @Override
            public void AudioPermissionError() {
                //没有录取权限回调
                Log.i("CJT", "AudioPermissionError");
            }
        });

        //左边按钮点击事件
        jCameraView.setLeftClickListener(new ClickListener() {
            @Override
            public void onClick() {
                SharedPreferences sp = getSharedPreferences("issafe", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("safe", false);
                editor.apply();
                DiyCameraActivity.this.finish();
            }
        });
        //JCameraView监听
        jCameraView.setJCameraLisenter(new JCameraListener() {

            @Override
            public void captureSuccess(Bitmap bitmap) {
                //获取图片bitmap
                Log.i("JCameraView", "bitmap = " + bitmap.getWidth());
                //保存图片
                saveImageToGallery(getApplicationContext(), bitmap);
                //返回图片
                String path = FileUtil.saveBitmap("MyPictureOrFilm", bitmap);
                Intent intent = new Intent();
                intent.putExtra(ImageContants.DIY_CAMERA_PATH, path);
                setResult(ImageContants.RESULT_CODE_IMAGE, intent);
                finish();

            }

            @Override
            public void recordSuccess(String url, Bitmap firstFrame) {
                //获取到url,duiurl进行处理拿到文件名,
                Log.i("CJT", "url = " + url);
                String videoNames[] = url.split("/");
                String videoName = videoNames[url.split("/").length - 1];
                String trueName = videoName.split("\\.")[0];
                //保存视频
                try {
                    //拿到文件大小
                    FileInputStream fis = null;
                    fis = new FileInputStream(new File(url));
                    long s = fis.available();
                    SharedPreferences sp = getSharedPreferences("videoVerify", Context
                            .MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putLong(trueName, s);
                    editor.apply();
                    //通知相册刷新
                    updateVideo(url);
                    Log.i("CJT", trueName + " = " + s);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //返回视频
                Intent intent = new Intent();
                intent.putExtra(ImageContants.DIY_CAMERA_SHEXIANG_PATH, url);
                setResult(ImageContants.CAMERA_SHEXIANG_REQUEST, intent);
                finish();
            }


        });
        //右边按钮点击事件
        jCameraView.setRightClickListener(new ClickListener() {
            @Override
            public void onClick() {
                Toast.makeText(DiyCameraActivity.this, "Right", Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        //全屏显示
        if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        } else {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(option);
        }
    }

    @Override
    protected void beforSetContentView(Bundle savedInstanceState) {
        super.beforSetContentView(savedInstanceState);
        cachePath = getIntent().getStringExtra("cachePath");
        isNeedVideo = getIntent().getBooleanExtra("isNeedVideo", true);
        //这方法没啥用了,被我阉掉了,直接指定目录了
        if (cachePath == null) {
            cachePath = Environment.getExternalStorageDirectory().getPath() + File.separator +
                    "MyAppPic";
        } else {
            cachePath = Environment.getExternalStorageDirectory().getPath() + File.separator +
                    "MyAppPic";
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (granted) {
            jCameraView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        jCameraView.onPause();
    }


    public static void saveImageToGallery(final Context context, final Bitmap bmp) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 写子线程中的操作

                // 首先保存图片

                File appDir = new File(Environment.getExternalStorageDirectory().getPath() + File
                        .separator + "MyAppPic");
                if (!appDir.exists()) {
                    appDir.mkdir();
                }
                String trueName = "picture_" + System.currentTimeMillis();
                String fileName = trueName + ".jpg";
                File file = new File(appDir, fileName);
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(context.getContentResolver(),
                            file.getAbsolutePath(), fileName, null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // 最后通知图库更新
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse
                        ("file://" + file)));
                //保存图片信息留待以后验证
                try {
                    //拿到文件大小
                    FileInputStream fis = null;
                    fis = new FileInputStream(file);
                    long s = fis.available();
                    SharedPreferences sp = context.getSharedPreferences("pictureVerify", Context
                            .MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putLong(trueName, s);
                    editor.apply();

                    Log.i("CJT", trueName + " = " + s);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }


    /**
     * 隐藏系统ui
     */
    private void hindSystemUI() {
        decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE);
    }

    /**
     * 显示系统ui
     */
    private void showSystemUI() {
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

    /**
     * 可以保证 自动隐藏
     *
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //变成横屏了
            hindSystemUI();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            //变成竖屏了
            hindSystemUI();
        }
    }

    /**
     * 获取权限
     */
    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) ==
                            PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
                            PackageManager.PERMISSION_GRANTED) {
                //具有权限
                granted = true;
            } else {
                //不具有获取权限，需要进行权限申请
                ActivityCompat.requestPermissions(DiyCameraActivity.this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA}, GET_PERMISSION_REQUEST);
                granted = false;
            }
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == GET_PERMISSION_REQUEST) {
            int size = 0;
            if (grantResults.length >= 1) {
                int writeResult = grantResults[0];
                //读写内存权限
                boolean writeGranted = writeResult == PackageManager.PERMISSION_GRANTED;//读写内存权限
                if (!writeGranted) {
                    size++;
                }
                //录音权限
                int recordPermissionResult = grantResults[1];
                boolean recordPermissionGranted = recordPermissionResult == PackageManager
                        .PERMISSION_GRANTED;
                if (!recordPermissionGranted) {
                    size++;
                }
                //相机权限
                int cameraPermissionResult = grantResults[2];
                boolean cameraPermissionGranted = cameraPermissionResult == PackageManager
                        .PERMISSION_GRANTED;
                if (!cameraPermissionGranted) {
                    size++;
                }
                if (size == 0) {
                    granted = true;
                    jCameraView.onResume();
                } else {
                    Toast.makeText(this, "请到设置-权限管理中开启", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onClick(View v, int id) {

    }

    public void updateVideo(String url) {
        File file = new File(url);
        //获取ContentResolve对象，来操作插入视频
        ContentResolver localContentResolver = this.getContentResolver();
        //ContentValues：用于储存一些基本类型的键值对
        ContentValues localContentValues = getVideoContentValues(this, file, System
                .currentTimeMillis());
        //insert语句负责插入一条新的纪录，如果插入成功则会返回这条记录的id，如果插入失败会返回-1。
        Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                localContentValues);
    }

    //再往数据库中插入数据的时候将，将要插入的值都放到一个ContentValues的实例当中
    public static ContentValues getVideoContentValues(Context paramContext, File paramFile, long
            paramLong) {
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("title", paramFile.getName());
        localContentValues.put("_display_name", paramFile.getName());
        localContentValues.put("mime_type", "video/3gp");
        localContentValues.put("datetaken", Long.valueOf(paramLong));
        localContentValues.put("date_modified", Long.valueOf(paramLong));
        localContentValues.put("date_added", Long.valueOf(paramLong));
        localContentValues.put("_data", paramFile.getAbsolutePath());
        localContentValues.put("_size", Long.valueOf(paramFile.length()));
        return localContentValues;
    }
}
